package com.donar.concurrent.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by donar on 18/2/27.
 * 自旋锁 实现 synchronized
 * 自旋锁不停执行循环 不改变线程的运行状态 所以响应速度更快。但是线程数不停增加时性能明显下降,因为每个线程都需要执行,占用cpu时间。适用于竞争不激烈的场景
 * 这个例子的锁是非公平锁,获得锁的先后顺序不按照lock的先后顺序
 */
public class SpinLock {
    private AtomicReference<Thread> sign = new AtomicReference<Thread>();
    public void lock(){
        Thread current = Thread.currentThread();
        //并发情况下加入一个线程Thread1 持有了该锁  那么 sign 当先的值应该为持有该锁的线程Thread1  那个当Thread2需要持有该锁时 compareAndSet 返回就会一直为false 然后就一直循环等待锁释放
        while (!sign.compareAndSet(null,current)){}
    }
    public void unlock(){
        Thread current  = Thread.currentThread();
        //只有持有锁的线程才能释放锁 如果Thread1持有锁 Thread2调用unlock是不会成功的
        sign.compareAndSet(current,null);
    }

    public static void main(String[] args) throws InterruptedException {
        final SpinLock lock = new SpinLock();
        System.out.println("lock");
        lock.lock();
        Thread.sleep(5000);
        lock.unlock();
        System.out.println("unlock");
    }
}
